package org.summerframework.component.upload.ftp.pool;

import org.summerframework.component.upload.ftp.FtpProperties;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;

import java.util.function.Function;

/**
 * FastDFS 连接池工厂
 */
public class FtpConnectionPoolFactory {

    private GenericObjectPool<FTPClient> pool;

    public FtpConnectionPoolFactory(FtpProperties properties) {
        pool = new GenericObjectPool<>(new FtpConnectionFactory(properties));
        pool.setConfig(properties);
        pool.setTestOnBorrow(true);
        pool.setTestWhileIdle(true);
        pool.setTestOnReturn(true);
    }

    public FTPClient getServer() throws Exception {
        return pool.borrowObject();
    }

    public void releaseConnection(FTPClient ftpClient) {
        if (ftpClient == null) {
            return;
        }
        pool.returnObject(ftpClient);
    }

    public <T> T execute(Function<FTPClient, T> function) throws Exception {
        FTPClient server = getServer();
        try {

            return function.apply(server);
        } finally {
//            try {
//                server.completePendingCommand();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

            releaseConnection(server);
        }
    }
}
